#coding=utf-8
'''
你想排序类型相同的对象，但是他们不支持原生的比较操作
attrgetter
lambda
'''
class User:
    def __init__(self, user_id):
        self.user_id = user_id
    def __repr__(self):
        return 'User({})'.format(self.user_id)

users = [User(23), User(3), User(99)]
a = sorted(users, key=lambda u: u.user_id)
print(users)
print(a)

# Instead of using  lambda , an alternative approach is to use  operator.attrgetter()
from operator import attrgetter
b = sorted(users, key=attrgetter('user_id'))
print(b)

# attrgetter() is often a tad bit faster and also has the added
# feature of allowing multiple fields to be extracted simultaneously.
by_name = sorted(users, key=attrgetter('last_name', 'first_name'))

# It is also worth noting that the technique used in this recipe can be applied to functions
# such as  min() and  max()
c = min(users, key=attrgetter('user_id'))
d = max(users, key=attrgetter('user_id'))
print(c)
print(d)